package cn.iclass.modules.sys.service.impl;

import cn.iclass.common.constant.CommonConstant;
import cn.iclass.modules.sys.dao.SysMenuDao;
import cn.iclass.modules.sys.dao.SysUserDao;
import cn.iclass.modules.sys.entity.SysMenuEntity;
import cn.iclass.modules.sys.entity.SysUserEntity;
import cn.iclass.modules.sys.service.ShiroService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: ShiroServiceImpl.java
 * @Author: alan
 * @Date: 2019/6/10 5:22 PM
 */
@Service
public class ShiroServiceImpl implements ShiroService {
	@Resource
	private SysMenuDao sysMenuDao;
	@Resource
	private SysUserDao sysUserDao;

	@Override
	public Set<String> getUserPermissions(long userId) {
		List<String> permsList;

		//系统管理员，拥有最高权限
		if (userId == CommonConstant.SUPER_ADMIN) {
			List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
			permsList = new ArrayList<>(menuList.size());
			for (SysMenuEntity menu : menuList) {
				permsList.add(menu.getPerms());
			}
		} else {
			permsList = sysUserDao.queryAllPerms(userId);
		}
		//用户权限列表
		Set<String> permsSet = new HashSet<>();
		for (String perms : permsList) {
			if (StringUtils.isBlank(perms)) {
				continue;
			}
			permsSet.addAll(Arrays.asList(perms.trim().split(",")));
		}
		return permsSet;
	}


	@Override
	public SysUserEntity queryUser(Long userId) {
		return sysUserDao.selectById(userId);
	}
}
